import { Request } from 'express';
import { JwtPayload } from 'jsonwebtoken';

// 用户和权限相关类型
export interface User {
  id: string;
  username: string;
  email: string;
  password?: string;
  department: string;
  roles: string[];
  isActive: boolean;
  lastLoginAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

export interface Role {
  id: string;
  name: string;
  displayName: string;
  description: string;
  permissions: string[];
  isSystemRole: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface Permission {
  id: string;
  name: string;
  resource: string;
  action: string;
  description: string;
  createdAt: Date;
}

// JWT 相关类型
export interface TokenPayload extends JwtPayload {
  userId: string;
  username: string;
  roles: string[];
}

export interface AuthenticatedRequest extends Request {
  user?: User;
  token?: TokenPayload;
}

// 告警相关类型
export interface Alert {
  id: string;
  alertname: string;
  instance: string;
  severity: 'critical' | 'high' | 'medium' | 'low';
  status: 'firing' | 'resolved' | 'acknowledged';
  startsAt: Date;
  endsAt?: Date;
  description: string;
  summary: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  fingerprint: string;
  generatorURL?: string;
  aiAnalysis?: AIAnalysis;
  assignedTo?: string;
  ticketId?: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface AIAnalysis {
  confidence: number;
  tags: string[];
  category: string;
  rootCause?: string;
  impact: string;
  recommendation: string;
  priority: 'urgent' | 'high' | 'medium' | 'low';
  businessImpact: number;
  urgency: number;
  suggestedAssignee?: string;
  suggestedTags: string[];
  similarIssues?: string[];
  processedAt: Date;
}

// Prometheus 相关类型
export interface PrometheusQuery {
  query: string;
  time?: string;
  timeout?: string;
}

export interface PrometheusRangeQuery extends PrometheusQuery {
  start: string;
  end: string;
  step: string;
}

export interface PrometheusMetric {
  metric: Record<string, string>;
  value?: [number, string];
  values?: Array<[number, string]>;
}

export interface PrometheusResponse {
  status: 'success' | 'error';
  data: {
    resultType: 'matrix' | 'vector' | 'scalar' | 'string';
    result: PrometheusMetric[];
  };
  error?: string;
  warnings?: string[];
}

// 工单相关类型
export interface Ticket {
  id: string;
  title: string;
  description: string;
  status: 'created' | 'assigned' | 'in_progress' | 'pending' | 'resolved' | 'closed' | 'reopened';
  priority: 'urgent' | 'high' | 'medium' | 'low';
  assignee?: string;
  reporter: string;
  watchers: string[];
  labels: string[];
  relatedAlert?: string;
  linkedTickets: string[];
  sla: {
    target: number;
    remaining: number;
    status: 'on_track' | 'at_risk' | 'violated';
  };
  timeline: TimelineEvent[];
  attachments: Attachment[];
  createdAt: Date;
  updatedAt: Date;
  resolvedAt?: Date;
  closedAt?: Date;
}

export interface TimelineEvent {
  id: string;
  type: 'created' | 'assigned' | 'status_changed' | 'comment' | 'escalated';
  title: string;
  description: string;
  user: string;
  timestamp: Date;
  metadata?: Record<string, any>;
}

export interface Attachment {
  id: string;
  fileName: string;
  originalName: string;
  fileSize: number;
  mimeType: string;
  path: string;
  uploadedBy: string;
  uploadedAt: Date;
}

// 知识库相关类型
export interface KnowledgeItem {
  id: string;
  title: string;
  content: string;
  category: string;
  tags: string[];
  author: string;
  status: 'draft' | 'published' | 'archived';
  viewCount: number;
  likeCount: number;
  sources: KnowledgeSource[];
  createdAt: Date;
  updatedAt: Date;
}

export interface KnowledgeSource {
  type: 'ticket' | 'alert' | 'document' | 'external';
  id: string;
  title: string;
  url?: string;
}

export interface ChatMessage {
  id: string;
  type: 'user' | 'ai';
  content: string;
  timestamp: Date;
  sources?: KnowledgeSource[];
  userId: string;
  sessionId: string;
}

// API 响应类型
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    totalPages: number;
  };
}

export interface PaginationQuery {
  page?: number;
  pageSize?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

export interface FilterQuery {
  search?: string;
  status?: string[];
  severity?: string[];
  assignee?: string[];
  dateRange?: {
    start: Date;
    end: Date;
  };
  tags?: string[];
}

// 系统配置类型
export interface SystemConfig {
  general: {
    siteName: string;
    timezone: string;
    language: string;
  };
  monitoring: {
    prometheusUrl: string;
    refreshInterval: number;
    retentionDays: number;
  };
  llm: {
    provider: 'openai' | 'claude' | 'custom';
    apiKey: string;
    model: string;
    temperature: number;
    maxTokens: number;
  };
  notifications: {
    email: boolean;
    sms: boolean;
    webhook: boolean;
    channels: NotificationChannel[];
  };
}

export interface NotificationChannel {
  id: string;
  name: string;
  type: 'email' | 'sms' | 'webhook' | 'dingtalk';
  config: Record<string, any>;
  enabled: boolean;
}

// WebSocket 事件类型
export interface WebSocketEvent {
  type: string;
  data: any;
  timestamp: Date;
  userId?: string;
}

// 日志类型
export interface LogEntry {
  level: 'error' | 'warn' | 'info' | 'debug';
  message: string;
  timestamp: Date;
  userId?: string;
  action?: string;
  resource?: string;
  metadata?: Record<string, any>;
}

// 统计数据类型
export interface Statistics {
  alerts: {
    total: number;
    critical: number;
    high: number;
    medium: number;
    low: number;
    resolved: number;
    unresolved: number;
    averageResponseTime: number;
    trend: number;
  };
  tickets: {
    total: number;
    created: number;
    assigned: number;
    inProgress: number;
    resolved: number;
    closed: number;
    averageResolutionTime: number;
    slaCompliance: number;
    trend: number;
  };
  system: {
    uptime: number;
    mtbf: number;
    mttr: number;
    availability: number;
  };
}

// 错误类型
export class AppError extends Error {
  public statusCode: number;
  public isOperational: boolean;

  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

// 环境变量类型
export interface EnvConfig {
  NODE_ENV: string;
  PORT: number;
  API_PREFIX: string;
  JWT_SECRET: string;
  JWT_EXPIRES_IN: string;
  JWT_REFRESH_EXPIRES_IN: string;
  MONGODB_URI: string;
  REDIS_URI: string;
  OPENAI_API_KEY: string;
  OPENAI_MODEL: string;
  OPENAI_TEMPERATURE: number;
  OPENAI_MAX_TOKENS: number;
  PROMETHEUS_URL: string;
  ALERTMANAGER_URL: string;
  SMTP_HOST?: string;
  SMTP_PORT?: number;
  SMTP_USER?: string;
  SMTP_PASS?: string;
  SMTP_FROM?: string;
  LOG_LEVEL: string;
  LOG_DIR: string;
  CORS_ORIGIN: string;
  RATE_LIMIT_WINDOW: number;
  RATE_LIMIT_MAX: number;
}